# coding: utf8

import os
import logging
import requests
import traceback
from multiprocessing.pool import ThreadPool


logging.basicConfig(level=logging.INFO)


class PostHelper(object):

    def __init__(self):
        self.pool = ThreadPool(os.cpu_count() * 2)

    def post_data(self, data):
        try:
            r = requests.post("http://127.0.0.1:8088", json=data)
            if r.status_code == 200:
                res = r.json()
                logging.info("post %s ok, row: %s", data['name'], res['row'])
            else:
                r.raise_for_status()
        except Exception as e:
            traceback.print_exc()
            raise e

    def post_expert_data(self, name, institute=None, department=None, title=None, degree=None, tel=None, email=None,
                         addr=None, avatar=None, edu=None, work=None, research=None, contribution=None, introduction=None, source=None, url=None):

        data = {'name': name, 'institute': institute, 'department': department, 'title': title, 'degree': degree, 'tel': tel, 'email': email, 'addr': addr, 'avatar': avatar, 'edu': edu, 'work': work, 'research': research, 'contribution': contribution, 'introduction': introduction, 'source': source, 'url': url}

        self.pool.apply_async(self.post_data, (data, ))

    def close(self):
        self.pool.close()
        self.pool.join()


def post_data(data):
    try:
        r = requests.post("http://127.0.0.1:8088", json={"i": data})
        if r.status_code == 200:
            logging.info("send %s", data)
        else:
            r.raise_for_status()

    except Exception as e:
        traceback.print_exc()
        raise e


def run_test():
    pool = ThreadPool(os.cpu_count() * 2)
    for i in range(100):
        pool.apply_async(post_data, (i,))

    pool.close()
    pool.join()


if __name__ == '__main__':
    run_test()

